/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.mleiria.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.Key;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author NB13712
 */
public class IOUtils {

    private final static Logger LOG = Logger.getLogger(IOUtils.class.getName());

    public static final void serializeKey(final Key key, final String pathAndFileName)
            throws FileNotFoundException, IOException {

        final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(pathAndFileName));
        out.writeObject(key);
        out.close();
    }

    public static final Key deSerializeKey(final String pathAndFileName)
            throws FileNotFoundException, IOException, ClassNotFoundException {

        final ObjectInputStream in = new ObjectInputStream(new FileInputStream(pathAndFileName));
        final Key key = (Key) in.readObject();
        in.close();
        return key;
    }

    public static String showFileContents(final String pathToFile) throws FileNotFoundException, IOException {
        final File f = new File(pathToFile);
        final FileInputStream fis = new FileInputStream(f);
        FileChannel fchannel = fis.getChannel();
        ByteBuffer bytebuf = ByteBuffer.allocate(1024);
        fchannel.read(bytebuf);
        bytebuf.flip();
        //LOG.info("Contents of file ");
        StringBuilder sb = new StringBuilder();
        while (bytebuf.hasRemaining()) {
            sb.append((char) bytebuf.get());
        }
        LOG.log(Level.INFO, "[{0}]", sb.toString());
        return sb.toString();
    }

    /**
     * load a file for neural networks, e.g., 1,0,0 1,0,1 1,1,0
     *
     * @param pathToFile
     * @param separator
     * @return
     * @throws java.io.FileNotFoundException
     */
    public static int[][] loadFileTo2DArray(final String pathToFile, final String separator) throws FileNotFoundException, IOException {

        final BufferedReader br = new BufferedReader(new FileReader(pathToFile));
        String line;
        final List<String[]> rows = new ArrayList<String[]>();
        if (null == separator) {
            while ((line = br.readLine()) != null) {
                rows.add(new String[]{line});
            }
        } else {
            while ((line = br.readLine()) != null) {
                rows.add(line.split(separator));
            }
        }

        br.close();

        int[][] data = new int[rows.size()][];
        for (int i = 0; i < rows.size(); i++) {
            final String[] sensors = rows.get(i);
            final int colSize = sensors.length;
            data[i] = new int[colSize];
            for (int j = 0; j < colSize; j++) {
                data[i][j] = Integer.parseInt(sensors[j]);
            }
        }
        return data;
    }

    /**
     * load a file into a matrix, 1.34,2.34,0.3 13.45,0.2231,1.33
     *
     * @param pathToFile
     * @param separator
     * @return
     * @throws java.io.FileNotFoundException
     */
    public static double[][] loadFileToComponents(final String pathToFile, final String separator) throws FileNotFoundException, IOException {

        final BufferedReader br = new BufferedReader(new FileReader(pathToFile));
        String line;
        final List<String[]> rows = new ArrayList<String[]>();

        while ((line = br.readLine()) != null) {
            rows.add(line.split(separator));
        }
        br.close();

        double[][] data = new double[rows.size()][];
        for (int i = 0; i < rows.size(); i++) {
            final String[] sensors = rows.get(i);
            final int colSize = sensors.length;
            data[i] = new double[colSize];
            for (int j = 0; j < colSize; j++) {
                data[i][j] = Double.parseDouble(sensors[j]);
            }
        }
        return data;
    }

    /**
     * load a file for neural networks, e.g., 1,0,1
     *
     * @param pathToFile
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static int[] loadFileToArray(final String pathToFile) throws FileNotFoundException, IOException {

        final BufferedReader br = new BufferedReader(new FileReader(pathToFile));
        String line;
        String[] tmp = null;
        if ((line = br.readLine()) != null) {
            tmp = line.split(",");
        }
        br.close();
        final int arrSize = tmp.length;
        int[] arr = new int[arrSize];
        for (int i = 0; i < arrSize; i++) {
            arr[i] = Integer.parseInt(tmp[i]);
        }
        return arr;
    }

    public static String fromHexaToString(String hex) {
        final StringBuilder output = new StringBuilder();
        for (int i = 0; i < hex.length(); i += 2) {
            String str = hex.substring(i, i + 2);
            output.append((char) Integer.parseInt(str, 16));
        }
        System.out.println(output);
        return output.toString();
    }

    public static void main(String[] args) {
        char a = 'a';
        byte aa = (byte) a;

    }

    public Map<Object, Number> loadFreqFromCsv(final String freqFile) {

        final Map<Object, Number> freq = new HashMap<Object, Number>();

        //Get file from resources folder
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource(freqFile).getFile());
        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                LOG.log(Level.INFO, "LINE-->{0}", line);
                String[] f = line.split(";");
                freq.put(f[0], Double.parseDouble(f[1]));

            }
            scanner.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return freq;
    }
}
